package com.vidmt.api.common.utils;

import java.lang.reflect.Method;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExecutionChain;

import com.vidmt.api.common.spring.MyDispatcherSerlet;

public class SpringUtil {
	private static final Logger log = LoggerFactory.getLogger(SpringUtil.class);

	public static ServletContext getServletContext() {
		return ContextLoader.getCurrentWebApplicationContext().getServletContext();
	}
	public static HttpServletRequest getRequest() {
		try {
			return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		} catch (Exception e) {
			return null;
		}
	}
	public static Method getHandler(String url) {

		MyDispatcherSerlet servlet = MyDispatcherSerlet.getInstance();
		ServletContext context = servlet.getServletContext();
		String ctxPath = context.getContextPath();
		url.replaceFirst(ctxPath, "");
		if (!url.startsWith("/")) {
			url = "/" + url;
		}
		if (!url.startsWith("/a/")) {
			url = "/a" + url;
		}
		
		HttpServletRequest req = new MockHttpServletRequest(context, "GET", url);
		try {
			HandlerExecutionChain chain = servlet.getHandler(req);
			if (chain == null) {
				return null;
			}
			Object handler = chain.getHandler();
			if (handler == null || !(handler instanceof HandlerMethod)) {
				return null;
			}
			return ((HandlerMethod) handler).getMethod();
		} catch (Exception e) {
			log.error("spring util error", e);
			return null;
		}
	}
}
